package com.mmg.controller;

import com.mmg.common.BaiduFaceApi;
import com.mmg.common.Result;
import com.mmg.entity.User;
import com.mmg.service.UserService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

/**
 * 人脸识别
 */
@RestController
@CrossOrigin
public class PhotoController {

    @Autowired
    UserService userService;

    @Autowired
    private BaiduFaceApi baiduFaceApi;

    /**
     * 人脸信息注册
     **/
    @PostMapping("/faceLogin")
    @ResponseBody
    public Result faceLogin(@RequestParam("file") MultipartFile file) {
        // 传入可选参数调用接口
        HashMap<String, Object> options = new HashMap<>();
        options.put("max_face_num", "3");
        options.put("match_threshold", "80");
        options.put("quality_control", "NORMAL");
        options.put("liveness_control", "NONE");
        options.put("max_user_num", "3");
        String image = getImages(file);
        String imageType = "BASE64";
        String groupIdList = "group1";
        // 人脸搜索 M:N 识别
        JSONObject res = baiduFaceApi.getAipFace().multiSearch(image, imageType, groupIdList, options);
        System.out.println(res.toString(2));
        int id;
        User user = null;
        try {
            id = res.getJSONObject("result").getJSONArray("face_list")
                    .getJSONObject(0).getJSONArray("user_list")
                    .getJSONObject(0).getInt("user_id");
            user = userService.getById(id);
        } catch (Exception e) {
            System.err.println("登入失败，图像不合格");
        }
        return Result.ok().data("data", user);
    }

    /**
     * 人脸信息注册
     **/
    @PostMapping("/registerFace")
    @ResponseBody
    public Result registered(@RequestParam("file") MultipartFile file,
                             @RequestParam("id") String id) {
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<>();
        options.put("user_info", "user's info");
        options.put("quality_control", "NORMAL");
        options.put("liveness_control", "NONE");
        options.put("action_type", "REPLACE");
        String image = getImages(file);
        String imageType = "BASE64";
        String groupId = "group1";
        String userId = id;
        // 人脸注册
        JSONObject res = baiduFaceApi.getAipFace().addUser(image, imageType, groupId, userId, options);
        System.out.println(res.toString(2));
        return Result.ok().data("data", res.get("result").toString());
    }

    /**
     * 返回图片
     **/
    public String getImages(MultipartFile file) {
        try {
            if (file == null) {
                throw new RuntimeException("您还没有选择图片!");
            }
            String fileName = file.getOriginalFilename();
            //根据当前时间生成文件名
            fileName = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()) + "." + fileName;
            //System.out.println(fileName);
            // 确定文件存放的路径
            String realPath = ResourceUtils.getURL("classpath:").getPath() + "/static/faces";
            //通过拼接的方式，拼出带有时间的路径
            String dateformat = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            String dateDirPath = realPath + "/" + dateformat;
            File dateDir = new File(dateDirPath + "/" + fileName);
            //如果当前日期的文件夹不存在则创建
            if (!dateDir.exists()) dateDir.mkdirs();
            // 存储文件
            file.transferTo(dateDir);
            byte[] fileContent = Files.readAllBytes(dateDir.toPath());
            return Base64Utils.encodeToString(fileContent);
        } catch (IOException e) {
            throw new RuntimeException("上传文件失败,服务器发生异常!", e);
        }
    }
}
